import os, sys
import threading
from fcntl import ioctl
from scapy import *

class local(threading.Thread):
	#def __init__(self, _sendcallback, _recvcallback, parameters):
	def __init__(self, parameters):

		self.PacketIdCount = 0
		self.RXQueue = []
		self.TXQueue = []

		threading.Thread.__init__(self)
		TUNSETIFF = 0x400454ca
		IFF_TUN   = 0x0001
		IFF_TAP   = 0x0002

		TUNMODE = IFF_TUN
		MODE = 0
		DEBUG = 0

		if parameters:
			self.parameters = parameters
		else:
			# Default parameters
			pass

		if parameters["iface"]:
			self.iface = parameters["iface"]
		else:
			return False

		self.f = os.open("/dev/net/tun", os.O_RDWR)
		self.ifs = ioctl(self.f, TUNSETIFF, struct.pack("16sH", self.iface+"%d", TUNMODE))
		self.ifname = self.ifs[:16].strip("\x00")
		os.popen("/sbin/ifconfig " + self.ifname + " up")
		print "Allocated interface %s. Configure it and use it" % self.ifname
		
	def recvpacket(self, packet):
		NewPacket = {}
		NewPacket["Id"] = self.PacketIdCount
		if self.PacketIdCount < 65535:
			self.PacketIdCount+=1
		else:
			self.PacketIdCount=0
		NewPacket["Data"] = packet
		self.RXQueue.append(NewPacket)
		return True

	def run(self):
		while 1:
			try:
			        # Set the tun interface!
			        sniff(prn=self.recvpacket, iface=self.ifname)
			except:
				print "Error sniffing " + iface + " retrying in 5 sec..."
			time.sleep(5)
		
	
